﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using BrainTechLLC;

namespace EventWindowHandler.Plugin
{
    public class RecordedEventInfoViewModel : ObservableCollection<ObjectEventInfoViewModel>
    {
        public RecordedEventInfo _eventInfo;

        public RecordedEventInfoViewModel(RecordedEventInfo eventInfo)
        {
            _eventInfo = eventInfo;

            var all = eventInfo.EventInfos.AllItems;

            for (int n = 0; n < all.Count; n++)
            {
                var vm = AddViewModel(all[n]);
            }
        }

        protected ObjectEventInfoViewModel AddViewModel(ObjectEventInfo eventInfo)
        {
            ObjectEventInfoViewModel vm = new ObjectEventInfoViewModel(eventInfo);
            this.Add(vm);
            return vm;
        }

        public List<ObjectEventInfo> ReadCurrentObjectEventInfos()
        {
            List<ObjectEventInfo> results = new List<ObjectEventInfo>();

            for (int n = 0; n < this.Count; n++)
            {
                results.Add(this[n]._info);
            }

            return results;
        }

        public bool ReconcileListDifferences(List<ObjectEventInfo> newList)
        {
            var oldList = ReadCurrentObjectEventInfos();
            List<ObjectEventInfo> itemsAdded;
            List<ObjectEventInfo> itemsRemoved;
            bool didSomething = false;

            if (!newList.CompareCollections(oldList, out itemsAdded, out itemsRemoved))
            {
                foreach (var removed in itemsRemoved)
                {
                    this.RemoveAll(true, (vm) => vm._info == removed);
                }

                foreach (var added in itemsAdded)
                {
                    AddViewModel(added);
                }

                didSomething = true;
            }
            
            for (int n = 0; n < this.Count; n++)
            {
                var eventInfo = this[n];
                eventInfo.ReconcileListDifferences(eventInfo._info.EventInfo.AllItems);
            }

            return didSomething;
        }

        public int TotalEventCount
        {
            get { return _eventInfo.Count; }
        }
    }
}
